package com.yonyou.cyxdms.basedata.service.service.configure;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yonyou.cloud.http.plus.remote.IRemoteInvoke;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.service.excel.*;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.bean.dto.ImportResultDto;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataDictConstants;
import com.yonyou.cyxdms.basedata.client.domains.vo.MQBaseVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.PackageCacheVO;
import com.yonyou.cyxdms.basedata.service.constant.BasedataCommonConstants;
import com.yonyou.cyxdms.basedata.service.constant.BasedataDictConstants;
import com.yonyou.cyxdms.basedata.service.dto.CarPriceDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.GeneralPackageDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.PackageImportDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.PackageModifyDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.PackageQueryDTO;
import com.yonyou.cyxdms.basedata.service.entity.basedata.BasedataPO;
import com.yonyou.cyxdms.basedata.service.entity.color.ColorPO;
import com.yonyou.cyxdms.basedata.service.entity.configurer.PackagePO;
import com.yonyou.cyxdms.basedata.service.entity.model.ModelPO;
import com.yonyou.cyxdms.basedata.service.entity.product.VsProductPO;
import com.yonyou.cyxdms.basedata.service.entity.product.VsProductPricePO;
import com.yonyou.cyxdms.basedata.service.repository.basedata.BasedataMapper;
import com.yonyou.cyxdms.basedata.service.repository.basedata.SystemParamMapper;
import com.yonyou.cyxdms.basedata.service.repository.configurer.PackageMapper;
import com.yonyou.cyxdms.basedata.service.repository.model.ModelMapper;
import com.yonyou.cyxdms.basedata.service.repository.option.VsOptionMapper;
import com.yonyou.cyxdms.basedata.service.repository.product.VsProductMapper;
import com.yonyou.cyxdms.basedata.service.repository.product.VsProductPriceMapper;
import com.yonyou.cyxdms.basedata.service.service.brand.BrandService;
import com.yonyou.cyxdms.basedata.service.service.color.ColorService;
import com.yonyou.cyxdms.basedata.service.service.model.ModelService;
import com.yonyou.cyxdms.basedata.service.service.series.SeriesService;
import com.yonyou.cyxdms.basedata.service.util.MQUtils;
import com.yonyou.cyxdms.basedata.service.util.MapUtils;
import com.yonyou.cyxdms.basedata.service.vo.CarPriceImportVO;
import com.yonyou.cyxdms.basedata.service.vo.brand.BrandDictVO;
import com.yonyou.cyxdms.basedata.service.vo.model.ModelDictVO;
import com.yonyou.cyxdms.basedata.service.vo.packages.PackageDictVO;
import com.yonyou.cyxdms.basedata.service.vo.packages.VehicleProductPackageVO;
import com.yonyou.cyxdms.basedata.service.vo.series.SeriesDictVO;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysmanage.client.service.login.DealerBrandService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 配置
 *
 * @author renwd
 * @since 2018/12/11
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class PackageServiceImpl implements PackageService {

    public static final Logger logger = LoggerFactory.getLogger(PackageServiceImpl.class);

    @Autowired
    private BrandService brandService;

    @Autowired
    private SeriesService seriesService;

    @Autowired
    private ModelService modelService;

    @Autowired
    private PackageMapper packageMapper;

    @Autowired
    private VsOptionMapper vsOptionMapper;


    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private ExcelGenerator excelService;

    @Autowired
    private ExcelRead<PackageImportDTO> excelPackageService;

    @Autowired
    private ExcelRead<CarPriceImportVO> carPriceImportService;

    @Autowired
    DealerBrandService dealerBrandService;

    @Autowired
    private PackageService packageService;

    @Autowired
    private BasedataMapper basedataMapper;

    @Autowired
    ColorService colorService;

    @Autowired
    VsProductPriceMapper vsProductPriceMapper;

    @Autowired
    VsProductMapper vsProductMapper;

    @Autowired
    SystemParamMapper systemParamMapper;

    @Autowired
    IRemoteInvoke iRemoteInvoke;

    @Autowired
    private RedisClient redisClient;

    /**
     * 按条件查询配置信息
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.DTO.basedata.PackageCacheVO>
     * @author renwd
     * @since 2018/12/11
     */
    @Override
    @Transactional(readOnly = true)
    public List<PackageCacheVO> queryPackageByCondition(Map<String, Object> queryParam) {
        List<Long> brandIdList = dealerBrandService.queryBrandIdList();
        queryParam.put(BasedataCommonConstants.DEALER_BRNAND_LIST, brandIdList);
        return packageMapper.queryPackageByCondition(queryParam);
    }

    /**
     * 根据车型Id查询车辆配置信息
     *
     * @param modelId
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.DTO.basedata.PackageCacheVO>
     * @author guorp
     * @since 2018/12/13
     */
    @Override
    public List<PackageCacheVO> getPackageByModelId(Long modelId) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return packageMapper.getPackageByModelId(modelId, loginInfo.getAppId(), loginInfo.getGroupCode());
    }

    /**
     * 查询配置信息（pc）
     *
     * @param page
     * @param packageQueryDTO
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public IPage<VehicleProductPackageVO> queryVehicleProductPackage(Page page, PackageQueryDTO packageQueryDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = packageQueryDTO.toMaps();
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        logger.info("查询配置IPage的queryParam:------------------{}", queryParam);
        /**
         * 配置数据放置redis
         */
        String appId = loginInfoDto.getAppId();
        String  messageFormat = MessageFormat.format(BasedataCommonConstants.PACKAGE_CACHE_PRODUCT_PACKAGEID, appId);
        Object packageData = redisClient.get(messageFormat);
        if (null == packageData) {
            LambdaQueryWrapper<PackagePO> packageParam = new QueryWrapper<PackagePO>().lambda();
            packageParam.eq(PackagePO::getAppId, appId).orderByAsc(PackagePO::getConfigCode,PackagePO::getConfigName);
            List<PackagePO> packageList = packageMapper.selectList(packageParam);
            List<PackageCacheVO> packageVOList = BeanMapperUtil.copyList(packageList, PackageCacheVO.class);
            redisClient.set(messageFormat, JSONUtil.objectToJson(packageVOList), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
        }
        page.setRecords(packageMapper.queryVehicleProductPackage(page, queryParam));
        return page;
    }



    /**
     * Dcs根据查询条件返回对应的配置数据
     *
     * @param page
     * @param queryParam
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.yonyou.cyxdms.basedata.service.vo.packages.VehicleProductPackageVO>
     * @author renwd
     * @since 2019/7/19
     */
    @Override
    public IPage<VehicleProductPackageVO> queryVehicleProductDcsPackage(Page page, Map<String, Object> queryParam) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfoDto.getOwnerCode(), loginInfoDto.getAppId(), loginInfoDto.getGroupCode());
        List<VehicleProductPackageVO> vehicleProductPackageVos = packageMapper.queryVehicleProductDcsPackage(page, queryParam);
        page.setRecords(vehicleProductPackageVos);
        return page;
    }

    /**
     * 新增配置
     *
     * @param packageModifyDTO
     * @return java.lang.Integer
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public Integer addPackage(PackageModifyDTO packageModifyDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<PackagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(PackagePO::getAppId, loginInfoDto.getAppId())
                .in(PackagePO::getOwnerCode, loginInfoDto.getOwnerCode())
                .and(obj ->
                        obj.eq(PackagePO::getConfigCode, packageModifyDTO.getConfigCode())
                                .or()
                                .eq(PackagePO::getConfigName, packageModifyDTO.getConfigName()));
        // 判断同一家店面中是否存在相同的配置代码或名称
        List<PackagePO> packagePos = packageMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(packagePos)) {
            throw new ServiceBizException(BasedataCommonConstants.PACKAGE_NOT_REPEAT);
        }
        PackagePO packagePo = BeanMapperUtil.copyProperties(packageModifyDTO, PackagePO.class);
        int insertSize = packageMapper.insert(packagePo);
        // 发送数据到MQ
        sendPackage(packagePo, BasedataCommonConstants.BIZ_PACKAGE_INSERT);
        // 删除redis缓存
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.PACKAGE_CACHE_PACKAGE_ALL, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
        redisClient.del(messageFormat);

        return insertSize;
    }

    /**
     * dcs新增配置
     *
     * @param packageModifyDTO
     * @return java.lang.Integer
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public Integer addDcsPackage(PackageModifyDTO packageModifyDTO) {
        String appId = BasedataCommonConstants.APP_ID_RL;
        String groupCode = "-1";
        QueryWrapper<PackagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(PackagePO::getAppId, appId)
                .and(obj ->
                        obj.eq(PackagePO::getConfigCode, packageModifyDTO.getConfigCode()));
        // 判断同一家店面中是否存在相同的配置代码或名称
        List<PackagePO> packagePos = packageMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(packagePos)) {
            return 0;
        }
        PackagePO packagePo = BeanMapperUtil.copyProperties(packageModifyDTO, PackagePO.class);
        packagePo.setDataSources(BasedataDictConstants.DATA_SOURCES_BY_SUPER);
        packagePo.setAppId(BasedataCommonConstants.APP_ID_RL);
        packagePo.setCompanyCode("-1");
        packagePo.setOwnerCode("-1");
        packagePo.setOwnerParCode("-1");
        packagePo.setIsIssue(BasedataDictConstants.IS_NO_SEND);
        packagePo.setStartType(BasedataDictConstants.STATUS_QY);
        packagePo.setValidStartDate(packageModifyDTO.getValidStartDate());
        packagePo.setValidEndDate(packageModifyDTO.getValidEndDate());
        int insertSize = packageMapper.insert(packagePo);
        // 删除redis缓存
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.PACKAGE_CACHE_PACKAGE_ALL, appId, groupCode);
        redisClient.del(messageFormat);
        String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, appId, BasedataCommonConstants.PRODUCT_REDIS_TYPE, BasedataCommonConstants.PRODUCT_REDIS_LEVEL);
        redisClient.del(productFormat);
        return insertSize;
    }

    /**
     * 配置数据发送到MQ
     *
     * @param packagePo
     * @author ysj
     * @date 2019/10/23
     */
    public void sendPackage(PackagePO packagePo, String bizId) {
        List<PackagePO> packageList = new ArrayList<>();
        packageList.add(packagePo);
        MQBaseVO<List<PackagePO>> packageMq = new MQBaseVO<>(packageList, packagePo.getAppId(), packagePo.getOwnerCode());
        MQUtils.sendMsg(packageMq.toMap(), bizId, systemParamMapper, iRemoteInvoke);
    }

    /**
     * 修改配置
     *
     * @param id
     * @param packageModifyDTO
     * @return java.lang.Integer
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public Integer modifyConfig(Long id, PackageModifyDTO packageModifyDTO) {
        String appId = BasedataCommonConstants.APP_ID_RL;
        String groupCode = "-1";
        PackagePO packagePo = packageMapper.selectById(id);
        if (packagePo != null) {
            QueryWrapper<PackagePO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(PackagePO::getAppId, appId)
                    .notIn(PackagePO::getPackageId, id)
                    .and(obj ->
                            obj.eq(PackagePO::getConfigCode, packageModifyDTO.getConfigCode()));
            // 判断同一家店面中是否存在相同的配置代码或名称
            List<PackagePO> packagePos = packageMapper.selectList(queryWrapper);
            if (!CommonUtils.isNullOrEmpty(packagePos)) {
                return 0;
            } else {
                packagePo.setBrandId(packageModifyDTO.getBrandId());
                packagePo.setSeriesId(packageModifyDTO.getSeriesId());
                packagePo.setModelId(packageModifyDTO.getModelId());
                packagePo.setConfigCode(packageModifyDTO.getConfigCode());
                packagePo.setConfigName(packageModifyDTO.getConfigName());
                packagePo.setIsValid(packageModifyDTO.getIsValid());
                packagePo.setIsIssue(BasedataDictConstants.IS_NO_SEND);
                packagePo.setValidStartDate(packageModifyDTO.getValidStartDate());
                packagePo.setValidEndDate(packageModifyDTO.getValidEndDate());
                int updateSize = packageMapper.updateById(packagePo);
                // 删除redis缓存
                String messageFormat = MessageFormat.format(BaseDataCommonConstants.PACKAGE_CACHE_PACKAGE_ALL, appId, groupCode);
                redisClient.del(messageFormat);
                // 发送数据到MQ
//                sendPackage(packagePo, BasedataCommonConstants.BIZ_PACKAGE_UPDATE);
                return updateSize;
            }
        } else {
            throw new ServiceBizException("后台不存在该配置！");
        }

    }

    /**
     * dcs修改配置
     *
     * @param id
     * @param packageModifyDTO
     * @return java.lang.Integer
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public Integer modifyDcsConfig(Long id, PackageModifyDTO packageModifyDTO) {
        String appId = BasedataCommonConstants.APP_ID_RL;
        String groupCode = "-1";
        PackagePO packagePo = packageMapper.selectById(id);
        if (packagePo != null) {
            packagePo.setBrandId(packageModifyDTO.getBrandId());
            packagePo.setSeriesId(packageModifyDTO.getSeriesId());
            packagePo.setModelId(packageModifyDTO.getModelId());
            packagePo.setConfigCode(packageModifyDTO.getConfigCode());
            packagePo.setConfigName(packageModifyDTO.getConfigName());
            packagePo.setIsValid(packageModifyDTO.getIsValid());
            packagePo.setIsIssue(BasedataDictConstants.IS_NO_SEND);
            packagePo.setValidStartDate(packageModifyDTO.getValidStartDate());
            packagePo.setValidEndDate(packageModifyDTO.getValidEndDate());
            packagePo.setStartType(BasedataDictConstants.STATUS_QY);
            packagePo.setUpdatedAt(null);
            int updateSize = packageMapper.updateById(packagePo);
            // 删除redis缓存
            String messageFormat = MessageFormat.format(BaseDataCommonConstants.PACKAGE_CACHE_PACKAGE_ALL, appId, groupCode);
            redisClient.del(messageFormat);
            String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, appId, BasedataCommonConstants.PRODUCT_REDIS_TYPE, BasedataCommonConstants.PRODUCT_REDIS_LEVEL);
            redisClient.del(productFormat);
            return updateSize;
        } else {
            throw new ServiceBizException("后台不存在该配置！");
        }
    }

    /**
     * 配置导出excel
     *
     * @param queryParam
     * @param request
     * @param response
     * @return void
     * @author renwd
     * @since 2019/7/15
     */
    @Override
    public void exportExcelForPackage(Map<String, Object> queryParam, HttpServletRequest request, HttpServletResponse response) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfoDto.getOwnerCode(), loginInfoDto.getAppId(), loginInfoDto.getGroupCode());

        List<Long> brandIdList = dealerBrandService.queryBrandIdList();
        queryParam.put(BasedataCommonConstants.DEALER_BRNAND_LIST, brandIdList);

        List<Map> resultList = packageMapper.exportExcelForPackage(queryParam);
        Map<String, List<Map>> excelData = new HashMap<>();
        excelData.put("配置信息", resultList);
        List<ExcelExportColumn> exportColumnList = new ArrayList<>();
        exportColumnList.add(new ExcelExportColumn("BRAND_NAME", "品牌名称"));
        exportColumnList.add(new ExcelExportColumn("SERIES_NAME", "车系名称"));
        exportColumnList.add(new ExcelExportColumn("MODEL_NAME", "车型名称"));
        exportColumnList.add(new ExcelExportColumn("CONFIG_CODE", "配置代码"));
        exportColumnList.add(new ExcelExportColumn("CONFIG_NAME", "配置名称"));
        exportColumnList.add(new ExcelExportColumn("IS_VALID", "是否有效", ExcelDataType.Dict));
        excelService.generateExcel(excelData, exportColumnList, "配置信息.xls", request, response);
    }

    /**
     * 配置下拉框查询
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.packages.PackageDictVO>
     * @author renwd
     * @since 2019/7/16
     */
    @Override
    public List<PackageDictVO> queryPackageDict(Map<String, Object> queryParam) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfo.getOwnerCode(), loginInfo.getAppId(), loginInfo.getGroupCode());
        queryParam.put("orgType", loginInfo.getOrgType());
        queryParam.put("isValid", BaseDataDictConstants.IS_VALID);
        return packageMapper.queryPackageDict(queryParam);
    }

    /**
     * 导入配置
     *
     * @param importFile
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.PackageImportDTO>
     * @author renwd
     * @since 2019/7/22
     */
    @Override
    public List<PackageImportDTO> importPackages(MultipartFile importFile) {
        ImportResultDto<PackageImportDTO> importResult = null;
        try {
            importResult = excelPackageService.analyzeExcelFirstSheet(importFile,
                    new AbstractExcelReadCallBack<>(PackageImportDTO.class, this::addConfigImport));
            return importResult.getDataList();
        } catch (IOException e) {
            logger.error("import error:{}", e);
        }
        return Collections.emptyList();
    }

    /**
     * 导入销售指导价
     * 2019/11/27 + 新增 分类代码、储备高限、储备低限、销售底价的导入功能
     *
     * @param importFile
     * @return
     * @author ysj
     * @date 2019/09/20
     */
    @Override
    public ImportResultDto<CarPriceImportVO> importCarPrice(MultipartFile importFile) {
        logger.debug("开始导入销售指导价----importFile:{}", importFile);
        try {
            return carPriceImportService.analyzeExcelFirstSheet(importFile,
                    new AbstractExcelReadCallBack<>(CarPriceImportVO.class, this::insertCarPrice));
        } catch (IOException e) {
            logger.error("import error:{}", e);
        }
        return null;
    }

    /**
     * 修改销售指导价
     *
     * @param carPriceDTO
     * @return
     * @author ysj
     * @date 2019/09/21
     */
    @Override
    public Integer editCarPrice(CarPriceDTO carPriceDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        LambdaQueryWrapper<VsProductPricePO> queryPrice = new QueryWrapper<VsProductPricePO>().lambda();
        queryPrice.eq(VsProductPricePO::getAppId, loginInfoDto.getAppId())
                .eq(VsProductPricePO::getOwnerCode, loginInfoDto.getOwnerCode())
                .eq(VsProductPricePO::getProductId, carPriceDTO.getProductId());
        VsProductPricePO vsProductPricePo = vsProductPriceMapper.selectOne(queryPrice);
        if (vsProductPricePo == null) {
            vsProductPricePo = new VsProductPricePO();
            setProductInfo(carPriceDTO, vsProductPricePo);
            vsProductPriceMapper.insert(vsProductPricePo);
        } else {
            setProductInfo(carPriceDTO, vsProductPricePo);
            vsProductPriceMapper.updateById(vsProductPricePo);
        }
        return 1;
    }

    /**
     * product_price info
     *
     * @param carPriceDTO
     * @param vsProductPricePo
     * @author renwd
     * @since 2019/12/26
     */
    private void setProductInfo(CarPriceDTO carPriceDTO, VsProductPricePO vsProductPricePo) {
        vsProductPricePo.setDirectivePrice(carPriceDTO.getVehiclePrice());
        vsProductPricePo.setProductId(carPriceDTO.getProductId());
        vsProductPricePo.setMaxReserve(carPriceDTO.getMaxReserve());
        vsProductPricePo.setMinReserve(carPriceDTO.getMinReserve());
        vsProductPricePo.setVehicleMarkupRate(carPriceDTO.getVehicleMarkupRate());
        vsProductPricePo.setBasedataId(carPriceDTO.getBaseId());
        vsProductPricePo.setSalesBasePrice(carPriceDTO.getSalesBasePrice());
    }

    /**
     * 新增产品价格
     *
     * @param carPriceImportVO
     * @author ysj
     * @date 2019/09/20
     */
    private void insertCarPrice(CarPriceImportVO carPriceImportVO, boolean isValidateSuccess) {
        logger.info("carPriceImportVO:---------{}", carPriceImportVO);
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        LambdaQueryWrapper<VsProductPO> query = new QueryWrapper<VsProductPO>().lambda();
        query.eq(VsProductPO::getProductCode, carPriceImportVO.getProductCode());
        VsProductPO vsProductPo = vsProductMapper.selectOne(query);
        if (vsProductPo != null) {
            Long basedataId = null;
            if (!StringUtils.isNullOrEmpty(carPriceImportVO.getBaseCode())
                    && !StringUtils.isEquals(carPriceImportVO.getBaseCode(), BasedataCommonConstants.NULL_STRING)) {
                LambdaQueryWrapper<BasedataPO> queryWrapper = new QueryWrapper<BasedataPO>().lambda();
                queryWrapper.eq(BasedataPO::getAppId, loginInfoDto.getAppId())
                        .eq(BasedataPO::getOwnerCode, loginInfoDto.getOwnerCode())
                        .eq(BasedataPO::getBasedataType, carPriceImportVO.getBaseCode().trim());
                BasedataPO basedataPo = basedataMapper.selectOne(queryWrapper);
                if (basedataPo != null) {
                    basedataId = basedataPo.getBasedataId();
                } else {
                    throw new ServiceBizException("分类代码不存在");
                }
            }
            //新增/修改销售指导价
            if (isValidateSuccess) {
                updateCarPrice(loginInfoDto, vsProductPo.getProductId(), basedataId, carPriceImportVO);
            }
        } else {
            throw new ServiceBizException("产品代码不存在");
        }
    }

    /**
     * 新增或修改销售指导价
     *
     * @param loginInfoDto 登录信息
     * @param productId    产品ID
     * @param basedataId        销售指导价
     * @auhtor ysj
     * @date 2019/09/21
     */
    private void updateCarPrice(LoginInfoDto loginInfoDto, Long productId, Long basedataId, CarPriceImportVO carPriceImportVO) {
        LambdaQueryWrapper<VsProductPricePO> queryPrice = new QueryWrapper<VsProductPricePO>().lambda();
        queryPrice.eq(VsProductPricePO::getAppId, loginInfoDto.getAppId());
        queryPrice.eq(VsProductPricePO::getOwnerCode, loginInfoDto.getOwnerCode());
        queryPrice.eq(VsProductPricePO::getProductId, productId);
        VsProductPricePO vsProductPricePo = vsProductPriceMapper.selectOne(queryPrice);
        //同一个APPID,OWNERCODE下只会有一条产品价格数据
        if (vsProductPricePo == null) {
            vsProductPricePo = new VsProductPricePO();
            setVsPricePro(vsProductPricePo, basedataId, carPriceImportVO, productId);
            vsProductPriceMapper.insert(vsProductPricePo);
        } else {
            setVsPricePro(vsProductPricePo, basedataId, carPriceImportVO, productId);
            vsProductPriceMapper.updateById(vsProductPricePo);
        }
    }

    /**
     * 设置经销商整车维护信息
     *
     * @param vsProductPricePo
     * @param basedataId
     * @param carPriceImportVO
     * @author：chenzb
     * @since：2019-11-27
     */
    private void setVsPricePro(VsProductPricePO vsProductPricePo, Long basedataId, CarPriceImportVO carPriceImportVO, Long productId) {
        Double price = carPriceImportVO.getPrice();
        Integer maxReserve = carPriceImportVO.getMaxReserve();
        Integer minReserve = carPriceImportVO.getMinReserve();
        Double salesBasePrice = carPriceImportVO.getSalesBasePrice();
        if (price != null) {
            vsProductPricePo.setDirectivePrice(price);
        }
        vsProductPricePo.setProductId(productId);
        if (maxReserve != null) {
            vsProductPricePo.setMaxReserve(maxReserve);
        }
        if (minReserve != null) {
            vsProductPricePo.setMinReserve(minReserve);
        }
        if (basedataId != null) {
            vsProductPricePo.setBasedataId(basedataId);
        }
        if (salesBasePrice != null) {
            vsProductPricePo.setSalesBasePrice(salesBasePrice);
        }
    }

    /**
     * 导入配置
     *
     * @param rowDto
     * @return void
     * @author renwd
     * @since 2019/7/22
     */
    private void addConfigImport(PackageImportDTO rowDto, boolean isValidateSucess) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<PackagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PackagePO::getConfigCode, rowDto.getConfigCode())
                .eq(PackagePO::getAppId, loginInfoDto.getAppId())
                .in(PackagePO::getOwnerCode, loginInfoDto.getOwnerCode(), loginInfoDto.getGroupCode(), "-1");
        List<PackagePO> list = packageMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(list)) {
            throw new ServiceBizException("配置代码或名称不能重复");
        }

        brandService.existsBrand(rowDto.getBrandName());
        seriesService.existsSeries(rowDto.getSeriesName());
        ModelPO modelPo = modelService.existsSeries(rowDto.getModelName());

        PackagePO packagePo = new PackagePO();
        packagePo.setModelId(modelPo.getModelId());
        packagePo.setConfigCode(rowDto.getConfigCode());
        packagePo.setConfigName(rowDto.getConfigName());
        packagePo.setTaxPurchasePrice(Double.valueOf(rowDto.getTaxPurchasePrice()));

        String dataSources = rowDto.getDataSources();
        if (StringUtils.isNullOrEmpty(dataSources)) {
            packagePo.setDataSources(null);
        } else if ("店面".equals(dataSources)) {
            packagePo.setDataSources(10451001);
        } else if ("主机厂".equals(dataSources)) {
            packagePo.setDataSources(10451002);
        } else if ("集团".equals(dataSources)) {
            packagePo.setDataSources(10451003);
        } else {
            throw new ServiceBizException("数据来源不存在");
        }

        String isValid = rowDto.getIsValid();
        if (StringUtils.isNullOrEmpty(isValid)) {
            packagePo.setIsValid(null);
        } else if ("是".equals(isValid)) {
            packagePo.setIsValid(10041001);
        } else if ("否".equals(isValid)) {
            packagePo.setIsValid(10041002);
        } else {
            throw new ServiceBizException("是否有效类型不存在");
        }

        if (isValidateSucess) {
            packageMapper.insert(packagePo);
            //发送数据到MQ
            sendPackage(packagePo, BasedataCommonConstants.BIZ_PACKAGE_INSERT);
        }
    }

    /**
     * @Description: 根据Code获取配置
     * @Param: [modelId, appId, packageCode]
     * @Return: com.yonyou.cyxdms.basedata.service.vo.packages.PackageDictVO
     * @Author: lijun
     * @Date: 16:06 2019/8/22
     **/
    @Override
    public PackageDictVO getByCode(String appId, Long modelId, String packageCode) {
        return packageMapper.getByCode(appId, modelId, packageCode);
    }

    /**
     * @Description: 获取活动车型名称
     * @Param: [appId, brandCode, seriesCode, modelCode, packageCode]
     * @Return: String
     * @Author: lijun
     * @Date: 16:55 2019/9/10
     **/
    @Override
    public String getModelName(String appId, String brandCode, String seriesCode,
                               String modelCode, String packageCode, String colorCode) {
        if (StringUtils.isBlank(appId) || StringUtils.isBlank(brandCode)) {
            return "";
        }

        StringBuilder sb = new StringBuilder();

        BrandDictVO brand = brandService.getByCode(appId, brandCode);
        sb.append(brand.getBrandName());

        if (brand != null && brand.getBrandId() != null && !StringUtils.isBlank(seriesCode)) {
            if ("0".equals(seriesCode)) {
                sb.append("/不限");
            } else {
                SeriesDictVO series = seriesService.getByCode(appId,
                        Long.parseLong(String.valueOf(brand.getBrandId())), seriesCode);
                sb.append("/" + series.getSeriesName());

                if (series != null && series.getSeriesId() != null && !StringUtils.isBlank(modelCode)) {
                    if ("0".equals(modelCode)) {
                        sb.append("/不限");
                    } else {
                        ModelDictVO model = modelService.getByCode(appId,
                                Long.parseLong(String.valueOf(series.getSeriesId())), modelCode);
                        sb.append("/" + model.getModelName());

                        if (model != null && model.getModelId() != null && !StringUtils.isBlank(packageCode)) {
                            if ("0".equals(packageCode)) {
                                sb.append("/不限");
                            } else {
                                PackageDictVO packageVo = packageService.getByCode(appId,
                                        Long.parseLong(String.valueOf(model.getModelId())), packageCode);
                                sb.append("/" + packageVo.getConfigName());

                                if ("0".equals(colorCode)) {
                                    sb.append("/不限");
                                } else {
                                    ColorPO colorPo = colorService.getByCode(appId, colorCode);
                                    sb.append("/" + colorPo.getColorName());
                                }
                            }
                        }
                    }
                }
            }
        }

        return sb.toString().trim();
    }

    /**
     * JK获取id与code映射数据
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/9/10
     */
    @Override
    public Map<Long, String> queryPackageMapping(String appId) {
        Map<Long, String> map = new HashMap<>();
        LambdaQueryWrapper<PackagePO> query = new QueryWrapper<PackagePO>().lambda();
        query.eq(PackagePO::getAppId, appId);
        List<PackagePO> packagePoList = packageMapper.selectList(query);
        for (PackagePO packagePo : packagePoList) {
            map.put(packagePo.getPackageId(), packagePo.getConfigCode());
        }
        return map;
    }

    /**
     * 通用-新增/更新配置
     *
     * @author：chenzb
     * @since：2019-10-12
     */
    @Override
    public void addPackageGeneral(List<GeneralPackageDTO> generalPackageDtos) {

        logger.debug("厂端同步至后台的配置数据:{}", generalPackageDtos);
        if (CollectionUtils.isNotEmpty(generalPackageDtos)) {
            // 数据不为空遍历存储
            for (GeneralPackageDTO generalPackageDTO : generalPackageDtos) {
                QueryWrapper<PackagePO> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(PackagePO::getAppId, generalPackageDTO.getAppId())
                        .eq(PackagePO::getSourceId, generalPackageDTO.getSourceId());
                PackagePO oldPackagePo = packageMapper.selectOne(queryWrapper);
                // appId和modelCode获取到车型信息
                QueryWrapper<ModelPO> modelWrapper = new QueryWrapper<>();
                modelWrapper.lambda().eq(ModelPO::getAppId, generalPackageDTO.getAppId())
                        .eq(ModelPO::getModelCode, generalPackageDTO.getModelCode());
                ModelPO modelPo = modelMapper.selectOne(modelWrapper);
                String ownerCode = StringUtils.isBlank(generalPackageDTO.getOwnerCode()) ? "-1" : generalPackageDTO.getOwnerCode();
                // ownerCode设值-1 标记车厂下发
                if (oldPackagePo == null) {
                    // 新增配置
                    PackagePO packagePo = BeanMapperUtil.copyProperties(generalPackageDTO, PackagePO.class);
                    //设置售后冗余的字段
                    packagePo.setModelId(modelPo.getModelId());
                    packagePo.setOwnerCode(ownerCode);
                    packagePo.setCompanyCode(ownerCode);
                    packagePo.setOwnerParCode(ownerCode);
                    packagePo.setSourceChangedAt(LocalDateTime.now());
                    packagePo.setCreatedAt(LocalDateTime.now());
                    packagePo.setIsValid(10041001);
                    logger.debug("开始新增插入配置数据:{}", packagePo);
                    packageMapper.insert(packagePo);
                } else {
                    // 更新配置
                    PackagePO packagePo = BeanMapperUtil.copyProperties(generalPackageDTO, PackagePO.class);
                    packagePo.setOwnerCode(ownerCode);
                    packagePo.setCompanyCode(ownerCode);
                    packagePo.setOwnerParCode(ownerCode);
                    packagePo.setModelId(modelPo.getModelId());
                    packagePo.setPackageId(oldPackagePo.getPackageId());
                    packagePo.setUpdatedAt(LocalDateTime.now());
                    packagePo.setCreatedBy("-1");
                    packagePo.setIsValid(generalPackageDTO.getIsValid());
                    packagePo.setRecordVersion(oldPackagePo.getRecordVersion());
                    packagePo.setIsDeleted(generalPackageDTO.getIsDelete() == null ? 0 : generalPackageDTO.getIsDelete());
                    logger.debug("开始更新车型数据:{}", modelPo);
                    packageMapper.updateById(packagePo);
                }
            }
        } else {
            throw new ServiceBizException("厂端传来的配置数据的缺失！");
        }
    }

    /**
     * 获取所有配置
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/11/4
     */
    @Override
    public List<PackageCacheVO> getAllPackageByAppId(String appId) {
        LambdaQueryWrapper<PackagePO> query = new QueryWrapper<PackagePO>().lambda().eq(PackagePO::getAppId, appId);
        List<PackagePO> packagePoList = this.packageMapper.selectList(query);
        return BeanMapperUtil.copyList(packagePoList, PackageCacheVO.class);
    }
    /**
     * 选装导出
     *
     * @param:
     * @return:
     * @auther: wansht
     * @since: 2020/12/15
     */
    @Override
    public void exportExcelForOption(Map<String, Object> queryParam, HttpServletRequest request, HttpServletResponse response) {
        {
            LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
            MapUtils.addParameter(queryParam, loginInfoDto.getOwnerCode(), loginInfoDto.getAppId(), loginInfoDto.getGroupCode());
            List<Long> brandIdList = dealerBrandService.queryBrandIdList();
            queryParam.put(BasedataCommonConstants.DEALER_BRNAND_LIST, brandIdList);
            List<Map> resultList = vsOptionMapper.exportExcelForOption(queryParam);
            Map<String, List<Map>> excelData = new HashMap<>();
            excelData.put("选装信息", resultList);
            List<ExcelExportColumn> exportColumnList = new ArrayList<>();
            exportColumnList.add(new ExcelExportColumn("BRAND_NAME", "品牌名称"));
            exportColumnList.add(new ExcelExportColumn("SERIES_NAME", "车系名称"));
            exportColumnList.add(new ExcelExportColumn("MODEL_NAME", "车型名称"));
            exportColumnList.add(new ExcelExportColumn("CONFIG_NAME", "配置名称"));
            exportColumnList.add(new ExcelExportColumn("OPTION_CODE", "选装代码"));
            exportColumnList.add(new ExcelExportColumn("OPTION_NAME", "选装名称"));
            exportColumnList.add(new ExcelExportColumn("IS_VALID", "是否有效", ExcelDataType.Dict));
            excelService.generateExcel(excelData, exportColumnList, "选装信息.xls", request, response);
        }
    }

    /**
     * 新增编辑界面厂端配置下拉框
     *
     * @param brandsId
     * @param seriesId
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public List<VehicleProductPackageVO> queryPackageDictAll(String brandsId, String seriesId,String modelsId) {
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("seriesId", seriesId);
        queryParam.put("brandsId", brandsId);
        queryParam.put("modelsId", modelsId);
        return packageMapper.queryPackageDictAll(queryParam);
    }

    /**
     * 根据查询条件返回配置
     *
     * @param packageQueryDTO
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.packages.VehicleProductPackageVO>
     * @author caozx
     * @since 2020/12/8
     */
    @Override
    public List<VehicleProductPackageVO> queryVehicleProductPackage(PackageQueryDTO packageQueryDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = packageQueryDTO.toMaps();
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        logger.info("查询配置IPage的queryParam:------------------{}", queryParam);
        return packageMapper.queryVehicleProductPackage(queryParam);
    }

}
